//
//  PywIAPPayManager.m
//  PywSdk
//
//  Created by Jade on 16/9/6.
//  Copyright © 2016年 zero. All rights reserved.
//

#import "PywIAPPayManager.h"
#import "PywPayInfoModel.h"
#import "PywCreateOrderApi.h"
#import "AIFCreateOrderManager.h"
#import "PywMBProgressHUD+Pyw.h"
#import "PywCreateOrderApi.h"
#import "PywIAPHelper.h"
#import "PywCPNotifications.h"
#import "PywSdk+pay.h"
#import "PywCancelOrderApi.h"
@interface PywIAPPayManager()
@property (nonatomic,strong) PywPayInfoModel *payInfoModel;
@property (nonatomic,strong) PywCreateOrderApi *createOrderApi;
@property (nonatomic,strong) PywCancelOrderApi *cancelOrderApi;
@property (nonatomic,assign) BOOL orderCreating;//正在生成订单
@property (nonatomic,copy) NSString *tmp_productid;//临时记录计费点
@end

@implementation PywIAPPayManager

- (void)dealloc
{
    [[NSNotificationCenter defaultCenter] removeObserver:self];
}

+ (id)manger
{
    static id manger = nil;
    static dispatch_once_t onceToken;
    dispatch_once(&onceToken, ^{
        manger = [[[self class] alloc] init];
    });
    return manger;
}
- (instancetype)init
{
    self = [super init];
    if (self) {
        [self addNotifications];
    }
    return self;
}

#pragma mark - setUp

/**
 *  赋值支付参数信息
 *
 *  @param payInfo <#payInfo description#>
 */
- (void)setUpPayInfoModel:(NSDictionary *)payInfo
{
    PywPayInfoModel *payInfoModel = [[PywPayInfoModel alloc] init];
    payInfoModel.order = payInfo[@"order_id"];
    payInfoModel.amount = [payInfo[@"oriprice"] floatValue];
    payInfoModel.payMethod = PAY_WAY_TYPE_APPLE;
    payInfoModel.couponAmount = 0.00;
    payInfoModel.finalAmount = payInfoModel.amount - payInfoModel.couponAmount;
    payInfoModel.productDescript = payInfo[@"gameBi"];
    payInfoModel.cpprams = payInfo[@"cpprams"];
    payInfoModel.cpprodid = payInfo[@"cpprodid"];
    payInfoModel.payType = 0;
    if (payInfoModel.cpprodid.length == 0) {
        payInfoModel.payType = 1;
    }
    payInfoModel.rolename = payInfo[@"rolename"];
    payInfoModel.service = payInfo[@"service"];
    payInfoModel.roleid = payInfo[@"roleid"];
    payInfoModel.serverArea = payInfo[@"serverArea"];
    
    self.payInfoModel = payInfoModel;
    [PywPaymentInfo sharedPaymentInfo].payType = payInfoModel.payType;
    
    
    [self setUp];
}

- (void)setUp
{
    [self getCreateOrderData];
}

#pragma mark - getter

- (PywCreateOrderApi *)createOrderApi
{
    if (!_createOrderApi) {
        _createOrderApi = [PywCreateOrderApi manager];
    }
    return _createOrderApi;
}

- (PywCancelOrderApi *)cancelOrderApi
{
    if (!_cancelOrderApi) {
        _cancelOrderApi = [PywCancelOrderApi manager];
    }
    return _cancelOrderApi;
}



- (void)addNotifications
{
    //      通知监听
    [[NSNotificationCenter defaultCenter] addObserver:self
                                             selector:@selector(payFinish:)
                                                 name:kPywPayNotification
                                               object:nil];
}


#pragma mark - Notifications

/**
 *  支付成功回调
 *
 *  @param notification <#notification description#>
 */
- (void)payFinish:(NSNotification *)notification
{
    self.orderCreating = NO;
    NSString *message = notification.object;
    [PywMBProgressHUD showSuccess:message];
    NSMutableDictionary *dict = [[NSMutableDictionary alloc] init];
    [dict setObject:@"支付完成" forKey:@"info"];
    [dict setObject:[NSNumber numberWithInt:PYW_PAY_STATE_SUCCESS] forKey:@"result"];
    [[NSNotificationCenter defaultCenter] postNotificationName:kPywCPPayNotification
                                                        object:nil
                                                      userInfo:dict];
    
    // 当聚合直接调用支付时，支付完成后，需要清除以下字段的存储
    if ([PywPlatformMain sharedPlatformMain].perfromPayType == PerfromPayType_Common) {
        [PywPlatformMain sharedPlatformMain].account = @"";
        [PywPlatformMain sharedPlatformMain].token = @"";
        [PywAppInfo sharedAppInfo].gameKey = @"";
        [PywAppInfo sharedAppInfo].gameId = @"";
        [PywAppInfo sharedAppInfo].apisecret = @"";
        
    }
}



#pragma mark - Request
/**
 *  生成订单
 */
- (void)getCreateOrderData
{
    if (self.orderCreating) {
        return;
    }
    @try {
//        [PywMBProgressHUD showMessage:@"正在支付..."];
        self.orderCreating = YES;
        //临时保存计费点
        self.tmp_productid = self.payInfoModel.cpprodid;
        WEAK_SELF;
        [self.createOrderApi getCreateOrderWithPayInfo:self.payInfoModel success:^(NSString *status, id anyObjct) {
            STRONG_SELF(weakSelf);
            NSDictionary *orderDict = (NSDictionary *)anyObjct;
            [strongSelf requestCreateOrderSuccess:orderDict];
        } fail:^(NSError *error) {
            self.orderCreating = NO;
        }];
    } @catch (NSException *exception) {
        PLog(@"生成订单失败");
        self.orderCreating = NO;
        [PywMBProgressHUD hideHUD];
    } @finally {
        
    }
}


#pragma mark - request finish
/**
 *  生成订单
 *
 *  @param dict <#dict description#>
 */
- (void)requestCreateOrderSuccess:(NSDictionary *)dict
{
    int resultCode = [[dict objectForKey:@"ack"] intValue];
    if (resultCode == 200) {
        Boolean msg = [dict[@"msg"] intValue];
        NSString *payCode = dict[@"data"];
        if (msg == 1) { //纯代金券支付
            NSString *orderNum = dict[@"data"][@"orderNum"];
            self.payInfoModel.orderNum = orderNum;
            self.payInfoModel.cancleOrder = orderNum;
            [[PywIAPHelper manager] startBuyProduct:self.tmp_productid
                                           orderNum:self.payInfoModel.orderNum];
        }
    }else{
        [PywMBProgressHUD hideHUD];
        [PywMBProgressHUD showError:@"创建订单失败!"];
    }
}

@end
